package br.com.felipeab.dexter.bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import br.com.felipeab.dexter.bo.PersistenceService;
import br.com.felipeab.dexter.domain.User;
import br.com.felipeab.dexter.expection.TransactionException;
import br.com.felipeab.dexter.expection.ValidationException;
import br.com.felipeab.dexter.faces.CrudController;
import br.com.felipeab.dexter.util.BundleHelper;
import br.com.felipeab.dexter.util.StringHelper;

/**
 * Classe UserBean
 * 
 * @author Felipe A. Braga <br>
 *         18/06/2012 01:41:45<br>
 * 
 */
@ViewScoped
@ManagedBean(name = "userBean")
public class UserBean extends CrudController<User> {

	private static final long serialVersionUID = -4105295686876914116L;

	private User domain;
	private String passwordConfirm;
	private PersistenceService persistenceService;

	@Override
	protected PersistenceService getPersistenceService() {
		if (persistenceService == null) {
			persistenceService = new PersistenceService();
		}
		return persistenceService;
	}

	@Override
	public User getDomain() {
		if (domain == null) {
			domain = new User();
		}
		return domain;
	}

	@Override
	public void setDomain(User domain) {
		this.domain = domain;
	}

	@Override
	protected void validate() throws ValidationException {
		if (!getDomain().getPassword().equals(getPasswordConfirm())) {
			throw new ValidationException(BundleHelper.getMessage("msg.error.passwordsDontMatch"));
		}
	}

	@Override
	protected void save() throws TransactionException {
		getDomain().setPassword(StringHelper.encryptText(getDomain().getPassword()));
		super.save();
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void existsDomain() throws ValidationException {
		List<User> list;
		User obj = new User();
		obj.setId(this.getDomain().getId());
		obj.setLogin(this.getDomain().getLogin());
		list = getPersistenceService().findByExample(obj);
		if (!list.isEmpty()) {
			for (User item : list) {
				if (item.getId() != this.getDomain().getId() && item.getLogin().equals(this.getDomain().getLogin())) {
					throw new ValidationException(BundleHelper.getMessageWithParam("msg.error.thereAlreadyExisty",
							BundleHelper.getMessage("label.user"), BundleHelper.getMessage("label.login")));
				}
			}
		}
	}

	public String getPasswordConfirm() {
		return passwordConfirm;
	}

	public void setPasswordConfirm(String passwordConfirm) {
		this.passwordConfirm = passwordConfirm;
	}
}
